
import { _decorator, Component, Node, Prefab, Camera, instantiate, Collider, CollisionEventType, ITriggerEvent, Vec3, v3, Quat } from 'cc';
import { IArea, ITroop, IMap, ICountry } from '../../../shared/gameClient/games/OccupationTheWarModels';
import { PHY_GROUP } from '../Const';
import { OTWTroopFlagComponent } from './OTWTroopFlagComponent';
import { OTWTroopData } from '../Data/OTWTroopData';
import { OTWTroopRenderComponent } from './OTWTroopRenderComponent';
import { OTWObjectComponent } from './OTWObjectComponent';
import { OTWGameData } from '../Data/OTWGameData';
import { OTWFlagComponent } from './OTWFlagComponent';
import { OTWAreaComponent } from './OTWAreaComponent';
const { ccclass, property } = _decorator;

@ccclass('OTWTroopComponent')
export class OTWTroopComponent extends OTWObjectComponent {
    objType = () => "Troop";
    public troopData: OTWTroopData | null = null;

    /**移动速度,每秒距离*/
    private moveSpeed: number = 1;

    private isMoving = false;
    public moveFrom: Vec3 = v3();
    public moveTo: Vec3 = v3();
    private moveDirV3:Vec3=new Vec3();
    private moveDir:Quat=new Quat();
    private distance: number = 0;
    private useSec: number = 0;
    private goSec: number = 0;

    private tmpPos: Vec3 = v3();

    onDestroy() {
        this.troopData = null;
    }

    public setMove(targetX: number, targetZ: number) {
        this.moveFrom.set(this.troopData!.troop.x, 0, this.troopData!.troop.z);
        this.moveTo.set(targetX, 0, targetZ);
        this.distance = Vec3.distance(this.moveFrom, this.moveTo);
        this.useSec = this.distance / this.moveSpeed;
        this.goSec = 0;
        this.isMoving = true;
        this.moveDirV3.set(this.moveFrom);
        this.moveDirV3.subtract(this.moveTo);
        Quat.fromViewUp(this.moveDir,this.moveDirV3, Vec3.UP);
        this.troopData!.renderNode.setRotation(this.moveDir);
    }

    start() {
        var collider = this.getComponentInChildren(Collider);
        collider?.setGroup(PHY_GROUP.Troop);
        collider?.setMask(0xffffffff);
    }

    public updateData(dt: number) {
        if (!this.troopData) return;
        if (this.isMoving) {
            this.goSec += dt;
            if (this.goSec > this.useSec) {
                //时间到,直接设为目标值
                this.isMoving = false;
                //this.tmpPos.set(this.moveTo);
                //this._result.currIsTarget = true;
                this.node.setPosition(this.moveTo);
            } else {
                //中间用线性差值
                Vec3.lerp(this.tmpPos, this.moveFrom, this.moveTo, this.goSec / this.useSec);
                this.node.setPosition(this.tmpPos);
            }
            this.troopData.troop.x = this.node.position.x;
            this.troopData.troop.z = this.node.position.z;
        }
    }
}
